#include "DeviceList.h"
#include "ui_DeviceList.h"

#include "Component/DeviceCard.h"
#include "Models/DeviceInformation.h"
#include "Tools/MyUrl.h"
#include "Tools/UiUpdateMediator.h"

#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>

DeviceList::DeviceList(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::DeviceList)
{
    ui->setupUi(this);

    this->InitUi();
    this->ui->pushButton_all->setStyleSheet(this->checkedButtonStyle);
    this->ui->pushButton_online->setStyleSheet(this->noCheckedButtonStyle);
    this->ui->pushButton_offline->setStyleSheet(this->noCheckedButtonStyle);

    connect(UiUpdateMediator::getInstance(), &UiUpdateMediator::updateDevice,this, &DeviceList::InitUi);
}

void DeviceList::clearGridLayout()
{
    if (this->ui->gridLayout == nullptr)
    {
        return;
    }

    QLayoutItem *item;
    while((item = this->ui->gridLayout->takeAt(0)) != nullptr)
    {
        QWidget *widget = item->widget();
        if (widget)
        {
            widget->setParent(nullptr);
            delete widget;
        }
        delete item;
    }
}

void DeviceList::InitUi()
{
    this->checkedButtonStyle = R"(
        QPushButton {
            background-color: #FFFFFF;
            border-radius: 10px;
            color: #333333;
            padding: 0 10px;
            border: none;
            font-size:12px
        }
        QPushButton:hover {

            background-color: #FFFFFF;
        }
        QPushButton:pressed {
            background-color: #FFFFFF;
        }
        QPushButton:disabled {
            background-color: #FFFFFF;
            border-color: #F0F0F0;
            color: #AAAAAA;
        }
    )";

    this->noCheckedButtonStyle = R"(
        QPushButton {
            background-color: #E0E0E0;
            border: none;
            border-radius: 10px;
            color: #333333;
            padding: 0 10px;
            font-size:12px
        }
        QPushButton:hover {
            background-color: #D0D0D0;
        }
        QPushButton:pressed {
            background-color: #C0C0C0;
        }
        QPushButton:disabled {
            background-color: #F0F0F0;
            color: #999999;
        }
    )";

    this->sendNetworkRequest(MyUrl::deviceSelect);
}

DeviceList::~DeviceList()
{
    delete ui;
}

void DeviceList::sendNetworkRequest(QUrl url)
{
    this->clearGridLayout();

    QNetworkAccessManager* manager = new QNetworkAccessManager();
    connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply* reply){
        QJsonParseError parseError;
        QJsonDocument jsonData = QJsonDocument::fromJson(reply->readAll(), &parseError);

        if (parseError.error != QJsonParseError::NoError)
        {
            qDebug() << "JSON 解析失败：" << parseError.errorString() << __LINE__ << __FILE_NAME__;
            return;
        }

        QJsonArray deviceArray = jsonData.array();

        int row = 0;
        int col = 0;
        const int maxCols = 3;

        for(const QJsonValue &value: deviceArray)
        {

            QJsonObject deviceJson = value.toObject();

            DeviceInformation* device_info = new DeviceInformation(
                deviceJson["device_id"].toString(),
                deviceJson["username"].toString(),
                deviceJson["create_time"].toString(),
                deviceJson["creator"].toString(),
                deviceJson["connection_status"].toInt(),
                deviceJson["is_enabled"].toInt()
            );

            DeviceCard* device_card = new DeviceCard(device_info, this);
            connect(device_card, &DeviceCard::updateUi, this, &DeviceList::InitUi);

            this->ui->gridLayout->update();
            this->ui->gridLayout->addWidget(device_card, row, col);

            col++;
            if (col >= maxCols)
            {
                col = 0;
                row++;
            }
        }
    });

    QNetworkRequest* request = new QNetworkRequest(QUrl(url));
    request->setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    manager->get(*request);
}

void DeviceList::on_pushButton_online_clicked()
{
    QUrl url = MyUrl::deviceSelect + "?connection_status=1";
    this->sendNetworkRequest(url);

    this->ui->pushButton_all->setStyleSheet(this->noCheckedButtonStyle);
    this->ui->pushButton_online->setStyleSheet(this->checkedButtonStyle);
    this->ui->pushButton_offline->setStyleSheet(this->noCheckedButtonStyle);
}


void DeviceList::on_pushButton_all_clicked()
{
    this->sendNetworkRequest(MyUrl::deviceSelect);

    this->ui->pushButton_all->setStyleSheet(this->checkedButtonStyle);
    this->ui->pushButton_online->setStyleSheet(this->noCheckedButtonStyle);
    this->ui->pushButton_offline->setStyleSheet(this->noCheckedButtonStyle);
}


void DeviceList::on_pushButton_offline_clicked()
{
    QUrl url = MyUrl::deviceSelect + "?connection_status=0";
    this->sendNetworkRequest(url);

    this->ui->pushButton_all->setStyleSheet(this->noCheckedButtonStyle);
    this->ui->pushButton_online->setStyleSheet(this->noCheckedButtonStyle);
    this->ui->pushButton_offline->setStyleSheet(this->checkedButtonStyle);
}

